<?php
namespace Common\Model;
use Think\Model;
class ChatModel extends Model {
	protected $connection = 'DB_BASE_DSN';
	protected $tableName = 'qyx_chat'; 
	
	public function getChatList($data){
		$map = array();
		if(!empty($data['searchKey'])){
			$map['chatname']  = array('like','%'.$data['searchKey'].'%');
		}
		
		if(!empty($data['chatIds']) && is_array($data['chatIds'])){
			$map['chatid']  = array('in' , $data['chatIds']);
		}
		
		if(!empty($data['entid']))
			$map['entid'] = $data['entid'];
			
		if(!empty($data['departid']))
			$map['departid'] = $data['departid'];
		
		if($data['statusFilter']==="1" || $data['statusFilter']==="0")
			$map['status'] = $data['statusFilter'];
		
		$total = $this->where($map)->count();
		$fields = array('chatid','chatname','grouptype','chattype','custid','introduce','amount','maxcustnum','custnum','status','createtime','updatetime');
		
		if(empty($data['sortField']))$data['sortField'] = "chatid";
		if(empty($data['sortOrder']))$data['sortOrder'] = "desc";
		
		if(empty($data['pageSize']) && empty($data['pageIndex']))
			$result = $this->field($fields)->where($map)->order("{$data['sortField']} {$data['sortOrder']}")->select();
		else 
			$result = $this->field($fields)->where($map)->order("{$data['sortField']} {$data['sortOrder']}")->limit($data['pageIndex']*$data['pageSize'] , $data['pageSize'])->select();
		
		
		return array('total'=>$total , 'data'=>$result);
	}
	
	
	public function getChatIds($chatid=0){
		$map['status'] = 1;
		
		if(!empty($chatid)){
			$map['chatid'] = $chatid;
		}	
		
		$result = $this->field('chatid')->where($map)->select();
			
		return $result;
	}
	
	
	public function addChat($data){
		$result = $this->add($data);
		return $result;
	}
	
	public function updateChat($data){
		$map['chatid'] = $data['chatid'];
		$data['updatetime'] = date("Y-m-d H:i:s");
		$result = $this->where($map)->save($data);
		return $result;
	}
	
	public function deleteChat($data){
		$map['chatid'] = $data['chatid'];
		$result = $this->where($map)->delete();
		return $result;
	}
	
	public function getChatInfoById($chatid){
		$map['chatid'] = $chatid;
		$fields = array('chatid','chatname','grouptype','chattype','custid','introduce','amount','maxcustnum','custnum','isopen','status','createtime','updatetime');
		$result = $this->field($fields)->where($map)->find();
		return $result;
	}
	
	public function custNumInr($chatid , $num){
		$sql = "update qyx_chat set custnum=custnum+{$num} where chatid = {$chatid}";
		$this->execute($sql);
		//UPDATE qyx_chat c,(SELECT COUNT(*) AS num , chatid FROM qyx_chat_cust GROUP BY chatid) n SET c.custnum=n.num WHERE c.chatid=n.chatid;
	}
	
	public function custNumDecr($chatid , $num){
		$sql = "update qyx_chat set custnum=custnum-{$num} where chatid = {$chatid}";
		$this->execute($sql);
	}
}


